package com.blustreaksw.cyclecoach.util;

import java.util.ArrayList;

/***********************************************************************
 * Helper class that manages a rolling average.
 * 
 * @author Tomas Rivera
 *
 ***********************************************************************/
public class RollingAverage {
	
	private ArrayList<Object> mList;
	private int mMaxSize;
	
	/********************************************************************************
	 * Default constructor.
	 * 
	 * @param	size
	 * 		Maximum count of objects that we will create a rolling average for.
	 * @return	RollingAverage object
	 ********************************************************************************/
	public RollingAverage(int size) {
		mMaxSize = size;
		mList = new ArrayList<Object>();
	}
	
	/********************************************************************************
	 * Calculate rolling average using type double.
	 * 
	 * @param	value
	 * 		Double value that we will add to the list that we use to calculate
	 * 		the rolling average.
	 * @return	double
	 ********************************************************************************/
	public double calcAvgDouble(double value) {
		double sum = 0;
		
		if(mList.size() < mMaxSize) {
			mList.add((Object) value);
		} else {
			// remove the value at the top of the list, then insert the new value
			mList.remove(0);
			mList.add((Object) value);
		}
		
		for(Object d : mList) {
			sum += (Double) d;
		}
		
		return (sum / ((double)mList.size())); 
	}
	
	/********************************************************************************
	 * Calculate rolling average using type int.
	 * 
	 * @param	value
	 * 		Integer value that we will add to the list that we use to calculate
	 * 		the rolling average.
	 * @return	int
	 ********************************************************************************/
	public int calcAvgInteger(int value) {
		int sum = 0;
		
		if(mList.size() < mMaxSize) {
			mList.add((Object) value);
		} else {
			// remove the value at the top of the list, then insert the new value
			mList.remove(0);
			mList.add((Object) value);
		}
		
		for(Object d : mList) {
			sum += (Integer) d;
		}
		
		return (sum / mList.size()); 
	}

}
